import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import {
  GameState,
  LevelConfig,
  GameSettings,
  ChessUnit,
  EnemyUnit,
  ChessUnitType,
  Position,
  GameStatus
} from '../types/game';
import { ChessRules } from '../utils/chessRules';
import { EnemySystem } from '../systems/EnemySystem';
import { SkillSystem, SkillType } from '../systems/SkillSystem';
import { MoodSystem, MoodItem, MoodType } from '../systems/MoodSystem';
import { StorageManager, PlayerProgress, StarRatingCalculator } from '../utils/storage';
import { VisualEffectsSystem } from '../systems/VisualEffectsSystem';

// 游戏状态Store接口
interface GameStore {
  // 当前游戏状态
  gameState: GameState;
  
  // 关卡配置
  currentLevel: LevelConfig | null;
  
  // 敌军系统
  enemySystem: EnemySystem | null;
  
  // 技能系统
  skillSystem: SkillSystem | null;
  moodSystem: MoodSystem | null;
  visualEffectsSystem: VisualEffectsSystem | null;
  
  // 游戏设置
  settings: GameSettings;
  
  // 玩家进度
   playerProgress: PlayerProgress;
  
  // 游戏控制方法
  initializeGame: (levelConfig: LevelConfig) => void;
  updateGameState: (updates: Partial<GameState>) => void;
  deployUnit: (unitType: ChessUnitType, position: Position) => boolean | { success: boolean; };
  removeUnit: (unitId: string) => void;
  upgradeUnit: (unitId: string) => boolean;
  selectUnit: (unitType?: ChessUnitType) => void;
  
  // 敌军管理
  addEnemy: (enemy: EnemyUnit) => void;
  removeEnemy: (enemyId: string) => void;
  updateEnemies: (enemies: EnemyUnit[]) => void;
  
  // 资源管理
  addChessSpirit: (amount: number) => void;
  spendChessSpirit: (amount: number) => boolean;
  
  
  updateSkillCooldowns: (deltaTime: number) => void;
  
  // 游戏流程控制
  pauseGame: () => void;
  resumeGame: () => void;
  restartGame: () => void;
  endGame: (status: 'victory' | 'defeat') => void;
  
  // 设置管理
  updateSettings: (settings: Partial<GameSettings>) => void;
  
  // 进度管理
  updateProgress: (levelId: string, progress: Partial<PlayerProgress>) => void;
  unlockLevel: (levelId: string) => void;
  
  // 游戏逻辑更新
  updateGameLogic: (deltaTime: number) => void;
  
  // 使用技能
  useSkill: (skillType: SkillType, targetPosition?: Position) => { success: boolean; message?: string; };
  
  // 获取技能状态
  getSkillStatus: (skillType: SkillType) => any | null;
  
  // 获取所有技能状态
  getAllSkillsStatus: () => any | null;
  
  // 强制增加技能能量（用于测试）
  addSkillEnergy: (skillType: SkillType, amount: number) => void;
  
  // 收集意境物品
  collectMoodItem: (position: Position) => { success: boolean; message?: string; };
  
  // 获取指定位置的意境物品
  getMoodItemAt: (position: Position) => MoodItem | null;
  
  // 获取意境统计
  getMoodStatistics: () => any | null;
  
  // 强制生成意境物品（用于测试）
  forceSpawnMoodItem: (type: MoodType, position?: Position) => MoodItem | null;
  
  // 完成关卡并保存进度
  completeLevel: (levelId: string, gameResult: any) => any;
  
  // 获取关卡进度
  getLevelProgress: (levelId: string) => any | null;
  
  // 检查关卡是否解锁
  isLevelUnlocked: (levelId: string) => boolean;
  
  // 获取玩家总体统计
  getPlayerStatistics: () => any;
  
  // 重置玩家进度
  resetPlayerProgress: () => void;
  
  // 导出游戏数据
  exportGameData: () => string;
  
  // 导入游戏数据
  importGameData: (jsonData: string) => boolean;
  
  // 获取视觉效果系统
  getVisualEffectsSystem: () => VisualEffectsSystem | null;
  
  // 创建视觉效果
   createVisualEffect: (type: string, position: Position, options?: any) => void;
   
   // 开始下一波敌军
   startNextWave: () => void;
}

// 默认游戏状态
const defaultGameState: GameState = {
  currentWave: 0,
  totalWaves: 0,
  playerHealth: 20,
  chessSpirit: 100,
  score: 0,
  gameTime: 0,
  units: [],
  enemies: [],
  skills: {
    fireAttack: { cooldown: 0, energy: 0, maxEnergy: 100 },
    reinforcement: { cooldown: 0, energy: 0, maxEnergy: 80 },
    inspire: { cooldown: 0, energy: 0, maxEnergy: 60 }
  },
  gameStatus: 'playing',
  gameSpeed: 1,
  lastUpdateTime: Date.now(),
  moodValue: 0,
  moodItems: []
};

// 默认游戏设置
const defaultSettings: GameSettings = {
  masterVolume: 0.8,
  sfxVolume: 0.7,
  musicVolume: 0.6,
  quality: 'high',
  fullscreen: false,
  showGrid: true,
  showPath: true
};

// 生成唯一ID
const generateId = () => Math.random().toString(36).substr(2, 9);

// 创建游戏Store
export const useGameStore = create<GameStore>()(persist(
  (set, get) => ({
    gameState: defaultGameState,
    currentLevel: null,
    enemySystem: null,
    skillSystem: null,
    moodSystem: null,
    visualEffectsSystem: null,
    settings: defaultSettings,
    playerProgress: StorageManager.getPlayerProgress(),

    // 初始化游戏
    initializeGame: (levelConfig: LevelConfig) => {
      // 清理旧的敌军系统
      const oldEnemySystem = get().enemySystem;
      if (oldEnemySystem) {
        oldEnemySystem.cleanup();
      }
       
      // 清理意境系统
       if (get().moodSystem) {
         get().moodSystem!.cleanup();
       }
       
       // 清理视觉效果系统
       if (get().visualEffectsSystem) {
         get().visualEffectsSystem!.cleanup();
       }

      // 创建新的敌军系统
      const enemySystem = new EnemySystem(levelConfig, {
        onEnemyReachEnd: (enemy) => {
          const state = get();
          set({
            gameState: {
              ...state.gameState,
              playerHealth: state.gameState.playerHealth - 1
            }
          });
          
          // 检查游戏是否失败
          if (state.gameState.playerHealth <= 1) {
            get().endGame('defeat');
          }
        },
        onEnemyKilled: (enemy) => {
          const state = get();
          set({
            gameState: {
              ...state.gameState,
              chessSpirit: state.gameState.chessSpirit + enemy.reward
            }
          });
        },
        onWaveCompleted: () => {
          const state = get();
          const waveInfo = state.enemySystem?.getCurrentWaveInfo();
          if (waveInfo) {
            set({
              gameState: {
                ...state.gameState,
                currentWave: waveInfo.waveIndex
              }
            });
          }
        },
        onAllWavesCompleted: () => {
          get().endGame('victory');
        }
      });

      // 创建新的技能系统
      const skillSystem = new SkillSystem(
        {
          fireAttack: { energy: 0, maxEnergy: 100, cooldown: 0 },
          reinforcement: { energy: 0, maxEnergy: 80, cooldown: 0 },
          inspire: { energy: 0, maxEnergy: 60, cooldown: 0 }
        },
        {
          onChessSpiritChange: (amount: number) => {
            const currentState = get();
            set({
              gameState: {
                ...currentState.gameState,
                chessSpirit: Math.max(0, currentState.gameState.chessSpirit + amount)
              }
            });
          },
          onCreateTempUnit: (position, duration) => {
            // 创建临时单位的逻辑
            const tempUnit: ChessUnit = {
              id: `temp_${Date.now()}`,
              type: 'soldier',
              position,
              level: 1,
              health: 50,
              maxHealth: 50,
              attackPower: 15,
              attackRange: 1,
              attackSpeed: 1000,
              cost: 0
            };
            
            const currentState = get();
            set({
              gameState: {
                ...currentState.gameState,
                units: [...currentState.gameState.units, tempUnit]
              }
            });
            
            // 设置定时器移除临时单位
            setTimeout(() => {
              const state = get();
              set({
                gameState: {
                  ...state.gameState,
                  units: state.gameState.units.filter(u => u.id !== tempUnit.id)
                }
              });
            }, duration);
          },
          onApplyUnitBuff: (buffType: string, duration: number) => {
            // 为所有友军单位添加buff
            const currentState = get();
            const buffedUnits = currentState.gameState.units.map(unit => ({
              ...unit,
              attackPower: buffType === 'inspire' ? unit.attackPower + 10 : unit.attackPower
            }));
            
            set({
              gameState: {
                ...currentState.gameState,
                units: buffedUnits
              }
            });
            
            // 设置定时器移除buff
            setTimeout(() => {
              const state = get();
              const restoredUnits = state.gameState.units.map(unit => ({
                ...unit,
                attackPower: buffType === 'inspire' ? unit.attackPower - 10 : unit.attackPower
              }));
              set({
                gameState: {
                  ...state.gameState,
                  units: restoredUnits
                }
              });
            }, duration);
          }
        }
       );
       
       // 创建新的视觉效果系统
       const visualEffectsSystem = new VisualEffectsSystem();
       
      // 创建新的意境系统
      const moodSystem = new MoodSystem(
        10, // 棋盘宽度
        9,  // 棋盘高度
        {
          onMoodCollected: (item: MoodItem) => {
            const currentState = get();
            const newMoodValue = currentState.gameState.moodValue + item.value;
            const newChessSpirit = Math.min(200, currentState.gameState.chessSpirit + Math.floor(item.value / 2));
            
            set({
              gameState: {
                ...currentState.gameState,
                moodValue: newMoodValue,
                chessSpirit: newChessSpirit,
                score: currentState.gameState.score + item.value * 5
              }
            });
            
            console.log(`收集到${item.type}，获得${item.value}点意境值！`);
          },
          onMoodExpired: (item: MoodItem) => {
            console.log(`${item.type}意境消散了...`);
          }
        }
      );

      set({
           currentLevel: levelConfig,
           enemySystem,
           skillSystem,
           moodSystem,
           visualEffectsSystem,
        gameState: {
          ...defaultGameState,
          totalWaves: levelConfig.waves.length,
          playerHealth: levelConfig.playerHealth,
          chessSpirit: levelConfig.initialChessSpirit,
          lastUpdateTime: Date.now()
        }
      });
    },

    // 更新游戏状态
    updateGameState: (updates: Partial<GameState>) => {
      set((state) => ({
        gameState: {
          ...state.gameState,
          ...updates,
          lastUpdateTime: Date.now()
        }
      }));
    },

    // 部署单位
    deployUnit: (unitType: ChessUnitType, position: Position) => {
      const state = get();
      const unitConfig = getUnitConfig(unitType);
      
      // 检查是否有足够的棋魂
      if (state.gameState.chessSpirit < unitConfig.baseStats.cost) {
        return false;
      }
      
      // 使用象棋规则验证部署位置
      const boardLayout = state.currentLevel?.boardLayout || [];
      const validationResult = ChessRules.canDeployUnit(
        unitType,
        position,
        state.gameState.units,
        boardLayout
      );
      
      if (!validationResult.canDeploy) {
        console.warn(`部署失败: ${validationResult.reason}`);
        return false;
      }
      
      // 创建新单位
      const newUnit: ChessUnit = {
        id: generateId(),
        type: unitType,
        position,
        level: 1,
        health: unitConfig.baseStats.health,
        maxHealth: unitConfig.baseStats.health,
        attackPower: unitConfig.baseStats.attackPower,
        attackRange: unitConfig.baseStats.attackRange,
        attackSpeed: unitConfig.baseStats.attackSpeed,
        cost: unitConfig.baseStats.cost
      };
      
      set((state) => ({
        gameState: {
          ...state.gameState,
          units: [...state.gameState.units, newUnit],
          chessSpirit: state.gameState.chessSpirit - unitConfig.baseStats.cost
        }
      }));
      
      return { success: true };
    },

    // 移除单位
    removeUnit: (unitId: string) => {
      set((state) => ({
        gameState: {
          ...state.gameState,
          units: state.gameState.units.filter(unit => unit.id !== unitId)
        }
      }));
    },

    // 升级单位
    upgradeUnit: (unitId: string) => {
      const state = get();
      const unit = state.gameState.units.find(u => u.id === unitId);
      
      if (!unit || unit.level >= 3) {
        return false;
      }
      
      const upgradeCost = Math.floor(unit.cost * 0.5 * unit.level);
      
      if (state.gameState.chessSpirit < upgradeCost) {
        return false;
      }
      
      set((state) => ({
        gameState: {
          ...state.gameState,
          units: state.gameState.units.map(u => 
            u.id === unitId 
              ? {
                  ...u,
                  level: u.level + 1,
                  attackPower: Math.floor(u.attackPower * 1.3),
                  maxHealth: Math.floor(u.maxHealth * 1.2),
                  health: Math.floor(u.maxHealth * 1.2)
                }
              : u
          ),
          chessSpirit: state.gameState.chessSpirit - upgradeCost
        }
      }));
      
      return true;
    },

    // 选择单位类型
    selectUnit: (unitType?: ChessUnitType) => {
      set((state) => ({
        gameState: {
          ...state.gameState,
          selectedUnit: unitType
        }
      }));
    },

    // 添加敌军
    addEnemy: (enemy: EnemyUnit) => {
      set((state) => ({
        gameState: {
          ...state.gameState,
          enemies: [...state.gameState.enemies, enemy]
        }
      }));
    },

    // 移除敌军
    removeEnemy: (enemyId: string) => {
      set((state) => ({
        gameState: {
          ...state.gameState,
          enemies: state.gameState.enemies.filter(enemy => enemy.id !== enemyId)
        }
      }));
    },

    // 更新敌军列表
    updateEnemies: (enemies: EnemyUnit[]) => {
      set((state) => ({
        gameState: {
          ...state.gameState,
          enemies
        }
      }));
    },

    // 增加棋魂
    addChessSpirit: (amount: number) => {
      set((state) => ({
        gameState: {
          ...state.gameState,
          chessSpirit: state.gameState.chessSpirit + amount
        }
      }));
    },

    // 消耗棋魂
    spendChessSpirit: (amount: number) => {
      const state = get();
      
      if (state.gameState.chessSpirit < amount) {
        return false;
      }
      
      set((state) => ({
        gameState: {
          ...state.gameState,
          chessSpirit: state.gameState.chessSpirit - amount
        }
      }));
      
      return true;
    },

    // 使用技能
     useSkillAdvanced: (skillType: SkillType, targetPosition?: Position) => {
      const state = get();
      const skill = state.gameState.skills[skillType];
      
      if (skill.energy < skill.maxEnergy || skill.cooldown > 0) {
        return false;
      }
      
      set((state) => ({
        gameState: {
          ...state.gameState,
          skills: {
            ...state.gameState.skills,
            [skillType]: {
              ...skill,
              energy: 0,
              cooldown: getSkillCooldown(skillType),
              lastUsedTime: Date.now()
            }
          }
        }
      }));
      
      return true;
    },

    // 更新技能冷却
    updateSkillCooldowns: (deltaTime: number) => {
      set((state) => {
        const skills = { ...state.gameState.skills };
        
        Object.keys(skills).forEach(key => {
          const skillKey = key as keyof typeof skills;
          if (skills[skillKey].cooldown > 0) {
            skills[skillKey] = {
              ...skills[skillKey],
              cooldown: Math.max(0, skills[skillKey].cooldown - deltaTime)
            };
          }
        });
        
        return {
          gameState: {
            ...state.gameState,
            skills
          }
        };
      });
    },

    // 暂停游戏
    pauseGame: () => {
      const state = get();
      if (state.enemySystem) {
        state.enemySystem.setPaused(true);
      }
      if (state.skillSystem) {
        state.skillSystem.setPaused(true);
      }
      if (state.moodSystem) {
         state.moodSystem.setPaused(true);
       }
       if (state.visualEffectsSystem) {
         state.visualEffectsSystem.setPaused(true);
       }
      set((state) => ({
        gameState: {
          ...state.gameState,
          gameStatus: 'paused'
        }
      }));
    },

    // 恢复游戏
    resumeGame: () => {
      const state = get();
      if (state.enemySystem) {
        state.enemySystem.setPaused(false);
      }
      if (state.skillSystem) {
        state.skillSystem.setPaused(false);
      }
      if (state.moodSystem) {
         state.moodSystem.setPaused(false);
       }
       if (state.visualEffectsSystem) {
         state.visualEffectsSystem.setPaused(false);
       }
      set((state) => ({
        gameState: {
          ...state.gameState,
          gameStatus: 'playing',
          lastUpdateTime: Date.now()
        }
      }));
    },

    // 重新开始游戏
    restartGame: () => {
      const state = get();
      if (state.currentLevel) {
        get().initializeGame(state.currentLevel);
        // 开始第一波
        setTimeout(() => {
          const newState = get();
          if (newState.enemySystem) {
            newState.enemySystem.startNextWave();
          }
        }, 1000);
      }
    },

    // 结束游戏
    endGame: (status: 'victory' | 'defeat') => {
      set((state) => ({
        gameState: {
          ...state.gameState,
          gameStatus: status
        }
      }));
    },

    // 更新设置
    updateSettings: (settings: Partial<GameSettings>) => {
      set((state) => ({
        settings: {
          ...state.settings,
          ...settings
        }
      }));
    },

    // 更新进度
    updateProgress: (levelId: string, progress: Partial<PlayerProgress>) => {
      set((state) => ({
        playerProgress: {
          ...state.playerProgress,
          [levelId]: {
            ...state.playerProgress[levelId],
            ...progress
          }
        }
      }));
    },

    // 解锁关卡
    unlockLevel: (levelId: string) => {
      set((state) => ({
        playerProgress: {
          ...state.playerProgress,
          [levelId]: {
            ...state.playerProgress[levelId],
            unlocked: true
          }
        }
      }));
    },

    // 开始下一波
    startNextWave: () => {
      const state = get();
      if (state.enemySystem) {
        state.enemySystem.startNextWave();
      }
    },

    // 更新游戏逻辑
    updateGameLogic: (deltaTime: number) => {
       const state = get();
       if (state.enemySystem && state.skillSystem && state.moodSystem && state.visualEffectsSystem && state.gameState.gameStatus === 'playing') {
         const enemies = state.enemySystem.update(deltaTime, state.gameState.units);
         
         // 更新技能系统
         const updatedSkills = state.skillSystem.update(deltaTime);
         
         // 更新意境系统
         const occupiedPositions = [
           ...state.gameState.units.map(unit => unit.position),
           ...enemies.map(enemy => enemy.position)
         ];
         const updatedMoodItems = state.moodSystem.update(deltaTime, occupiedPositions);
         
         // 更新视觉效果系统
         state.visualEffectsSystem.update(deltaTime);
         
         set({
           gameState: {
             ...state.gameState,
             enemies,
             skills: updatedSkills,
             moodItems: updatedMoodItems,
             lastUpdateTime: Date.now()
           }
         });
       }
     },

    // 使用技能
     useSkill: (skillType: SkillType, targetPosition?: Position) => {
       const state = get();
       if (!state.skillSystem) return { success: false, message: '技能系统未初始化' };
       
       const result = state.skillSystem.useSkill(skillType, targetPosition, state.gameState.chessSpirit);
       
       // 创建技能视觉效果
       if (result.success && targetPosition && state.visualEffectsSystem) {
         state.visualEffectsSystem.createSkillEffect(targetPosition, skillType);
       }
       
       return result;
     },

    // 获取技能状态
    getSkillStatus: (skillType: SkillType) => {
      const state = get();
      if (!state.skillSystem) return null;
      
      return state.skillSystem.getSkillStatus(skillType);
    },

    // 获取所有技能状态
    getAllSkillsStatus: () => {
      const state = get();
      if (!state.skillSystem) return null;
      
      return state.skillSystem.getAllSkillsStatus();
    },

    // 强制增加技能能量（用于测试）
    addSkillEnergy: (skillType: SkillType, amount: number) => {
      const state = get();
      if (state.skillSystem) {
        state.skillSystem.addSkillEnergy(skillType, amount);
      }
    },

    // 收集意境物品
     collectMoodItem: (position: Position) => {
       const state = get();
       if (!state.moodSystem) return { success: false, message: '意境系统未初始化' };
       
       const moodItem = state.moodSystem.getMoodItemAt(position);
       const result = state.moodSystem.collectMoodItem(position);
       
       // 创建收集视觉效果
       if (result.success && moodItem && state.visualEffectsSystem) {
         state.visualEffectsSystem.createMoodCollectEffect(position, moodItem.type);
       }
       
       return result;
     },

    // 获取指定位置的意境物品
    getMoodItemAt: (position: Position) => {
      const state = get();
      if (!state.moodSystem) return null;
      
      return state.moodSystem.getMoodItemAt(position);
    },

    // 获取意境统计
    getMoodStatistics: () => {
      const state = get();
      if (!state.moodSystem) return null;
      
      return state.moodSystem.getMoodStatistics();
    },

    // 强制生成意境物品（用于测试）
     forceSpawnMoodItem: (type: MoodType, position?: Position) => {
       const state = get();
       if (state.moodSystem) {
         return state.moodSystem.forceSpawnMoodItem(type, position);
       }
       return null;
     },

     // 完成关卡并保存进度
     completeLevel: (levelId: string, gameResult: {
       completed: boolean;
       score: number;
       time: number;
       healthRemaining: number;
       maxHealth: number;
       unitsUsed: number;
       skillsUsed: number;
       moodCollected: number;
       waveReached: number;
       maxWave: number;
     }) => {
       const state = get();
       
       // 构建统计数据
       const statistics = {
         totalUnitsDeployed: gameResult.unitsUsed,
         totalEnemiesDefeated: state.gameState.enemies.length,
         totalSkillsUsed: gameResult.skillsUsed,
         totalMoodCollected: gameResult.moodCollected,
         maxWaveReached: gameResult.waveReached,
         averageHealthRemaining: gameResult.healthRemaining / gameResult.maxHealth
       };
       
       // 更新关卡进度
       const result = StorageManager.updateLevelProgress(levelId, {
         ...gameResult,
         statistics
       });
       
       // 更新游戏统计
       StorageManager.updateGameStatistics({
         completed: gameResult.completed,
         playTime: gameResult.time,
         score: gameResult.score,
         unitsUsed: gameResult.unitsUsed,
         skillsUsed: gameResult.skillsUsed,
         moodCollected: gameResult.moodCollected
       });
       
       // 更新状态
       set({ playerProgress: result.progress });
       
       return result;
     },

     // 获取关卡进度
     getLevelProgress: (levelId: string) => {
       const state = get();
       return state.playerProgress.levels[levelId] || null;
     },

     // 检查关卡是否解锁
     isLevelUnlocked: (levelId: string) => {
       const state = get();
       return state.playerProgress.unlockedLevels.includes(levelId);
     },

     // 获取玩家总体统计
     getPlayerStatistics: () => {
       return StorageManager.getGameStatistics();
     },

     // 重置玩家进度
     resetPlayerProgress: () => {
       StorageManager.clearAllData();
       set({ playerProgress: StorageManager.getPlayerProgress() });
     },

     // 导出游戏数据
     exportGameData: () => {
       return StorageManager.exportData();
     },

     // 导入游戏数据
     importGameData: (jsonData: string) => {
       const success = StorageManager.importData(jsonData);
       if (success) {
         set({ playerProgress: StorageManager.getPlayerProgress() });
       }
       return success;
     },

     // 获取视觉效果系统
     getVisualEffectsSystem: () => {
       return get().visualEffectsSystem;
     },

     // 创建视觉效果
     createVisualEffect: (type: string, position: Position, options?: any) => {
       const state = get();
       if (state.visualEffectsSystem) {
         switch (type) {
           case 'unitDeploy':
             state.visualEffectsSystem.createUnitDeployEffect(position);
             break;
           case 'enemyDeath':
             state.visualEffectsSystem.createEnemyDeathEffect(position);
             break;
           default:
             if (options?.particleType) {
               state.visualEffectsSystem.createParticleEffect(
                 options.particleType,
                 position,
                 options.count || 10,
                 options
               );
             }
             break;
         }
       }
     }
  }),
  {
    name: 'chess-defense-game',
    partialize: (state) => ({
      settings: state.settings,
      playerProgress: state.playerProgress
    })
  }
));

// 辅助函数：获取单位配置
function getUnitConfig(unitType: ChessUnitType) {
  const configs = {
    soldier: {
      baseStats: { health: 100, attackPower: 20, attackRange: 1, attackSpeed: 1000, cost: 50 }
    },
    cannon: {
      baseStats: { health: 80, attackPower: 40, attackRange: 3, attackSpeed: 2000, cost: 80 }
    },
    horse: {
      baseStats: { health: 120, attackPower: 35, attackRange: 2, attackSpeed: 1500, cost: 100 }
    },
    chariot: {
      baseStats: { health: 150, attackPower: 50, attackRange: 4, attackSpeed: 1200, cost: 120 }
    },
    advisor: {
      baseStats: { health: 60, attackPower: 10, attackRange: 2, attackSpeed: 3000, cost: 70 }
    },
    minister: {
      baseStats: { health: 200, attackPower: 15, attackRange: 3, attackSpeed: 2500, cost: 150 }
    },
    general: {
      baseStats: { health: 300, attackPower: 80, attackRange: 3, attackSpeed: 800, cost: 300 }
    }
  };
  
  return configs[unitType];
}

// 辅助函数：获取技能冷却时间
function getSkillCooldown(skillType: string): number {
  const cooldowns = {
    fireAttack: 30000, // 30秒
    reinforcement: 45000, // 45秒
    inspire: 25000 // 25秒
  };
  
  return cooldowns[skillType as keyof typeof cooldowns] || 30000;
}